package com.endoc.phtotapplication.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Base64Utils {

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static void savebitmap(Bitmap bitmap)
    {

        //创建文件，因为不存在2级目录，所以不用判断exist，要保存png，这里后缀就是png，要保存jpg，后缀就用jpg
        File file=new File("/sdcard/1023.jpg");

        try {
            //文件输出流
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            //压缩图片，如果要保存png，就用Bitmap.CompressFormat.PNG，要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%，表示不压缩
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
            //写入，这里会卡顿，因为图片较大
            fileOutputStream.flush();
            //记得要关闭写入流
            fileOutputStream.close();
            //成功的提示，写入成功后，请在对应目录中找保存的图片
            //Toast.makeText(MainActivity.this,"写入成功！目录"+Environment.getExternalStorageDirectory()+"/mfw.png",Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //失败的提示
            //Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            //失败的提示
            //Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * @param base64Str base64字符串
     * @param path  储存的路径
     * @return
     */
    public  boolean base64ToFile(String base64Str,String path) {
        byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if(data[i] < 0){
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }


    public static byte[] getBitmapByte(Bitmap bitmap){
                 ByteArrayOutputStream out = new ByteArrayOutputStream();
               bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                 try {
                        out.flush();
                         out.close();
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
               return out.toByteArray();
             }


          public static Bitmap getBitmapFromByte(byte[] temp){
            if(temp != null){
                       Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
                        return bitmap;
                    }else{
                         return null;
                 }
           }

    /**
     * @param path 图片路径
     * @return  base64编码
     */
    public  String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_CLOSE);
         /*   try {
                //writeOcrStrtoFile(result,Environment.getExternalStorageDirectory() + "/" + StringData.casePath ,"baseImage.txt");
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            //生成本地文件测试
            //base64ToFile(result,"/sdcard/test0.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     2      * 根据byte数组，生成文件
     3      */
      public static void getFile(byte[] bfile, String filePath,String fileName) {
                 BufferedOutputStream bos = null;
                 FileOutputStream fos = null;
                 File file = null;
                 try {
                        File dir = new File(filePath);
                         if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
                               dir.mkdirs();
                             }
                         file = new File(filePath+fileName);
                       fos = new FileOutputStream(file);
                         bos = new BufferedOutputStream(fos);
                         bos.write(bfile);
                     } catch (Exception e) {
                        e.printStackTrace();
                     } finally {
                         if (bos != null) {
                                 try {
                                         bos.close();
                                     } catch (IOException e1) {
                                         e1.printStackTrace();
                                     }
                            }
                        if (fos != null) {
                                try {
                                         fos.close();
                                     } catch (IOException e1) {
                                         e1.printStackTrace();
                                     }
                            }
                    }
             }


}
